﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace TowerDefenderSilverlight
{
    public partial class MainPage : UserControl
    {

        private Grid g;
        Uri uri;

        public MainPage()
        {
            InitializeComponent();
            try
            {
                var test = Resources;
                uri = new Uri(App.Current.Host.Source, "Resources/Maps/Map1.xml");
                WebClient wc = new WebClient();
                wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
                wc.OpenReadAsync(uri);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
            }
        }

        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                XDocument doc = XDocument.Load("Resources/Maps/Map1.xml");
                DrawGrid(Data.FileManager.LoadMap(doc));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
            }
            
        }

        public Grid DrawGrid(Model.Map map)
        {
            g = new Grid();
            this.Content = g;
            g.Width = this.RenderSize.Width * 0.9;
            g.Height = this.RenderSize.Height * 0.8;
            g.Background = new SolidColorBrush(Colors.Green);
         //   g.ShowGridLines = true;

            for (int i = 0; i < map.Width; i++)
            {
                var c = new ColumnDefinition();
                g.ColumnDefinitions.Add(c);
            }
            for (int j = 0; j < map.Length; j++)
            {
                var r = new RowDefinition();
                g.RowDefinitions.Add(r);
            }

            foreach (var step in map.MapPath.Path)
            {
                Rectangle r = new Rectangle();
                r.Fill = new SolidColorBrush(Colors.Gray);
                r.SetValue(Grid.ColumnProperty, step.X - 1);
                r.SetValue(Grid.RowProperty, step.Y - 1);
                g.Children.Add(r);

            }
            return g;

        }
    }
}
